package 预科0104ChattingRoom_Q5;

/*使用基于 tcp 协议的编程模型实现多人同时在线聊天和传输文件，
        要求每个客户端将发 送的聊天内容和文件发送到服务器，
        服务器接收到后转发给当前所有在线的客户端。*/


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class ServerTest {

    public static ArrayList<Socket> sockets =new ArrayList<>();
    public static int socketNum = 0;
    public static String lockfilename = "D:/聊天室/";
    public static String severfile = "D:/聊天室/sever";
    public static void main(String[] args) {
        //创建ServerSocket类型的对象并提供端口号
        ServerSocket ss = null;
        BufferedReader bufferedReader = null;
        File file = new File(severfile);
        if(!file.exists()){
            file.mkdir();
            System.out.println("sever文件夹创建成功！");
        }
        else {
            System.out.println("sever文件夹已存在！");
        }

        try {


            ss = new ServerSocket(8888);

            //等待客户端连接，调用accept
            while (true) {
                System.out.println("等待客户端连接。。。。。");
                sockets.add(ss.accept()) ;
                System.out.println("连接成功！");
                bufferedReader = new BufferedReader(new InputStreamReader(sockets.get(socketNum).getInputStream()));
                String name = bufferedReader.readLine();
                System.out.println( name + "连接成功！");

                //输入输出流进行通信
                new ChatThread(socketNum,name).start();
                //System.out.println(sockets);
                socketNum++;
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(sockets!=null) {
            	 for(Socket socket : sockets){
                     if(null!=socket){
                         try {
                             socket.close();
                         } catch (IOException e) {
                             e.printStackTrace();
                         }

                     }
                 }
            }
           
            //关闭Socket
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
